package com.itheima.dubbo.mongodb.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.commons.pojo.mongo.Users;
import com.itheima.dubbo.interfaces.UsersApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author yaohu
 * @date 2021/12/12
 * @Version 1.0
 * @describe
 */
@Service
public class UsersApiImpl implements UsersApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加好友
     *
     * @param users
     */
    @Override
    public void addUsers(Users users) {
        mongoTemplate.save(users);
    }

    /**
     * 根据userId分页查询好友列表
     *
     * @param userId   用户id
     * @param page     分页页码
     * @param pageSize 页面条数
     * @param keyword
     * @return
     */
    @Override
    public List<Users> findUsersByUserId(Long userId, Integer page, Integer pageSize, String keyword) {
        if (StrUtil.isBlank(keyword)) {
            // 无关键词，做分页
            return mongoTemplate.find(Query.query(Criteria.where("userId").is(userId))
                    .with(PageRequest.of(page - 1, pageSize)), Users.class);
        }
        // 有关键词查全部
        return mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)), Users.class);
    }

    /**
     * 删除好友
     *
     * @param userId
     * @param friendId
     */
    @Override
    public void removeUser(Long userId, Long friendId) {
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId)),Users.class);
    }
}
